package project.dade.cn.bst.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import project.dade.cn.bst.R;
import project.dade.cn.bst.activity.ProductDtailActivity;
import project.dade.cn.bst.adapter.base.Goshopingadapter;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.GoshopingModel;
import project.dade.cn.bst.model.IndexInfoHots;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;

/**
 * Created by computer on 2016/3/8.
 */
public class PageFragment extends Fragment implements BGAOnRVItemClickListener ,BGARefreshLayout.BGARefreshLayoutDelegate {
    public static final String ARGS_ID = "tag_id";
    protected static String TAG =PageFragment.class.getSimpleName();
    public String name;
    public String id;
    private KProgressHUD hud;
    private Goshopingadapter goshopingadapter;
    @InjectView(R.id.error_layout)
    EmptyLayout  mErrorLayout;
    private BGARefreshLayout  mRefreshLayout;
    private int page = 1;
    public static PageFragment newInstance(GoshopingModel bean) {
        Bundle args = new Bundle();
        args.putString(ARGS_ID, bean.getId());
        PageFragment fragment = new PageFragment();
        fragment.setArguments(args);

        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString(ARGS_ID);
        if (AppUtil.isNetworkAvailable(getActivity())) {
            requestGetclass();
        } else {

            Snackbar.make(getView(), R.string.tips_network_error, Snackbar.LENGTH_SHORT).show();
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.id_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        goshopingadapter = new Goshopingadapter( recyclerView);
        recyclerView.setAdapter(goshopingadapter);
        mRefreshLayout=(BGARefreshLayout)view.findViewById(R.id.rl_recyclerview_refresh);
        mRefreshLayout.setDelegate(this);
        goshopingadapter.setOnRVItemClickListener(this);
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getActivity(), true));
        return view;
    }
    private void requestGetclass() {
        hud = KProgressHUD.create(getActivity())
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载")
                .setCancellable(true);
        hud.show();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("Cid", id);
        params.put("PageIndex",page+"");

        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.ProductClass).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mRefreshLayout.endRefreshing();
                        hud.dismiss();
                        ToastUtil.showShort(getActivity(), "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        mRefreshLayout.endRefreshing();
                        hud.dismiss();
                        LogUtil.i(TAG, "购物车商品：" + response);
                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                        LogUtil.i(TAG, "购物车商品：" + model.getData());
                        if (model != null && model.getResult() == 0) {
                            hud.dismiss();
                            //获取请求成功
                            List<IndexInfoHots> Dates = new ArrayList<>();
                            Dates = JSON.parseArray(model.getData(), IndexInfoHots.class);
                            goshopingadapter.setDatas(Dates);
                        } else {
                            mRefreshLayout.endRefreshing();
                            hud.dismiss();
                            ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "搜索结果"));

                        }
                    }

                });
    }

    @Override
    public void onRVItemClick(ViewGroup viewGroup, View view, int position) {
        Intent mIntentRegInfo = new Intent(getActivity(), ProductDtailActivity.class);
        mIntentRegInfo.putExtra("id",goshopingadapter.getItem(position).getProductId());
        startActivity(mIntentRegInfo);
    }
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        page=1;
        requestGetclass();
    }
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (AppUtil.isNetworkAvailable(getActivity())) {
            page++;
            requestAddGetClassMore();
        } else {
            mRefreshLayout.endLoadingMore();
            Snackbar.make(getView(), R.string.tips_network_error, Snackbar.LENGTH_SHORT).show();
        }
        return true;
    }
    private void requestAddGetClassMore() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("Cid", id);
        params.put("PageIndex",page+"");
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.ProductClass).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mRefreshLayout.endLoadingMore();
                        ToastUtil.showShort(getActivity(), "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        mRefreshLayout.endLoadingMore();
                        hud.dismiss();
                        LogUtil.i(TAG, "购物车商品：" + response);
                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                        LogUtil.i(TAG, "购物车商品：" + model.getData());
                        if (model != null && model.getResult() == 0) {
                            if (model.getResult() == 0) {
                                if (model.getData()==null) {
                                    ToastUtil.showShort(getActivity(), "已经没了哦");
                                    page--;
                                } else {
                                    mRefreshLayout.endRefreshing();
                                    //获取请求成功
                                    List<IndexInfoHots> Dates = new ArrayList<>();
                                    Dates = JSON.parseArray(model.getData(), IndexInfoHots.class);
                                    goshopingadapter.addMoreDatas(Dates);
                                }
                            }
                        } else {
                            mRefreshLayout.endLoadingMore();
                            page--;
                            ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "获取商品列表"));

                        }
                    }

                });
    }

}